#include <iostream>
#include <vector>

#include "UdpServer.hpp"

void Usage(std::string proc) {
  std::cout << "\n\tUsage: " << proc << " port[1024+]\n" << std::endl;
}

std::string EchoHandler(const std::string& datastr,const std::string& clientip,uint16_t clientport) {
  std::string echo_string = "["+clientip+":"+std::to_string(clientport)+" echo]# "+datastr;
  return echo_string;
}

bool isSave(const std::string& cmd) {
  std::vector<std::string> unsaves = {"rm", "while", "sudo",
                                            "mv", "cp",    "yum"};
  int pos = 0;
  for (auto& world : unsaves) {
    pos = cmd.find(world);
    if (pos != std::string::npos) {
      return false;
    }
  }
  return true;
}

std::string HandlerCommand(const std::string& cmd) {
  // 打开管道，执行命令
  if (!isSave(cmd)) {
    return "the cmd unsave";
  }
  FILE* fp = popen(cmd.c_str(), "r");
  if (!fp) {
    perror("popen");
    return "error";
  }

  std::string ret;
  char buffer[4096];

  // 循环读取命令输出
  while (true) {
    char* res = fgets(buffer, sizeof(buffer), fp);
    if (res == nullptr) break;   // 到达文件末尾，或出错
    ret += std::string(buffer);  // 将命令输出追加到返回字符串中
  }

  // 关闭管道，并获取命令执行的返回值
  int status = pclose(fp);
  if (status == -1) {
    perror("pclose");
    return "error";
  }

  // 返回命令执行结果
  return ret;
}

int main(int argc, char* argv[]) {
  if (argc != 2) {
    Usage(argv[0]);
    exit(0);
  }

  std::unique_ptr<UdpServer> svr(new UdpServer(std::stoi(argv[1])));  // 守卫智能指针
  svr->Init();
  // svr->Run(HandlerCommand);
  svr->Run(EchoHandler);
  return 0;
}